package com.eastcom.auth;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author nicolas
 * @time   2010-4-2 13:53:17
 */
public class AuthFilter implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String currentURL = request.getRequestURI();
        String targetURL = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());
        String ctx = request.getContextPath();
//        System.out.println(currentURL);
//        System.out.println(targetURL);
        HttpSession session = request.getSession(false);
        if (!"/".equals(targetURL) && !"/login.jsp".equals(targetURL) && !"/login_check.jsp".equals(targetURL) && !"logout.jsp".equals(targetURL)) {
            if (session == null || session.getAttribute("user") == null) {
//                response.sendRedirect(request.getContextPath() + "/");
                java.io.PrintWriter out = response.getWriter();
                out.println("<html>");
                out.println("<script>");
                out.println("window.open ('" + ctx + "/','_top')");
                out.println("</script>");
                out.println("</html>");
            }
        }
        filterChain.doFilter(request, response);
    }

    public void init(FilterConfig fc) throws ServletException {
    }
}
